<script setup name="Blog">
	import {ref, reactive} from 'vue'
	import {blogApi} from '@/api/blog.js'
	import {blogTypeApi} from "@/api/type.js";
	import {
		Plus,
		Delete,
		Edit,
		Message,
		Search,
		Download,
		Upload,
	} from '@element-plus/icons-vue'
	import {ElMessage, ElMessageBox} from "element-plus";
	
	//表格数据
	let blogList = ref([])
	const total = ref(0)
	
	//分页信息，搜索条件
	const blogQuery = reactive({
		page: 1,
		limit: 10,
		name: '',
		typeId: ''
	})
	
	const handleClick = (id) => {
		console.log('click')
		blogApi.selectById(id).then(result => {
			blog.value.content = result.data
		})
	}
	
	const loadData = () => {
		console.log('加载blog分页数据')
		blogApi.list(blogQuery).then(result => {
			console.log("Result.data：" + result.data)
			blogList.value = result.data.list
			total.value = result.data.total
			
		})
	}
	
	loadData()
	
	//分类数据
	const options = ref([])
	//获取分类数据
	const selectAllType = () => {
		blogTypeApi.selectAll().then(result => {
			options.value = result.data
		})
	}
	selectAllType()
	
	const onSearch = () => {
		blogQuery.page = 1
		loadData()
	}
	
	//单个删除
	const deleteById = (id) => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			.then(() => {
				blogApi.deleteById(id).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
			})
	}
	
	//批量删除
	const ids = ref([])
	const handleSelectionChange = (rows) => {
		//console.log('多选', rows)
		ids.value = rows.map(row => row.id)
		console.log(ids.value);
	}
	const deleteAll = () => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			//点击确认删除
			.then(() => {
				ids.value = ids.value.join(',')
				blogApi.deleteAll(ids.value).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
			})
	}
	
	//添加、编辑
	const dialogVisible = ref(false)
	const blog = ref({})
	const title = ref()
	const showAddDialog = () => {
		
		dialogVisible.value = true
		title.value = '添加'
		blog.value = {}
	}
	
	const showUpdateDialog = (id) => {
		dialogVisible.value = true
		title.value = '编辑'
		blog.value = {}
		blogApi.selectById(id).then(result => {
			blog.value = result.data
		})
	}
	
	const addOrUpdate = () => {
		if (blog.value.id) {  //有值，编辑
			blogApi.update(blog.value).then(result => {
				if (result.code === 0) {
					ElMessage({message: result.msg, type: 'success',})
					dialogVisible.value = false
				} else {
					ElMessage.error(result.msg)
				}
				//刷新表格
				loadData()
			})
		} else {   //无值，添加
			blogApi.add(blog.value).then(result => {
				if (result.code === 0) {
					ElMessage({message: result.msg, type: 'success',})
					dialogVisible.value = false
				} else {
					ElMessage.error(result.msg)
				}
				//刷新表格
				loadData()
			})
		}
	}
	
	//富文本编辑器
	const onEditorChange = (content) => {
		console.log(content)
		blog.value.content = content
	}
	import {useTokenStore} from '@/store/token.js'
	import WangEditor from "@/components/WangEditor.vue";
	
	const tokenStore = useTokenStore();
	const headers = ref({
		//携带token传递到后端
		Authorization: tokenStore.token
	});
	const handleAvatarSuccess = (result) => {
		blog.value.image = result.data
	}
	
	const handleSwitchChange = (row) => {
		blogApi.updateStatus(row.id, row.status).then(result => {
			if (result.code === 0) {
				ElMessage.success(result.msg)
			} else {
				ElMessage.error(result.msg)
			}
		})
	}
	
	const originData = () => ({name: "", typeId: "", beginUpdateTime: "", endUpdateTime: ""});
	const resetForm = () => {
		Object.assign(blogQuery, originData());
	};
	
	//导出Excel
	const exportExcel = () => {
		blogApi.exportExcel().then(result=>{
			let blob = new Blob([result], { type: "application/xlsx" });
			let url = window.URL.createObjectURL(blob);
			const link = document.createElement("a"); // 创建a标签
			link.href = url;
			link.download = "博客列表.xlsx"; // 重命名文件
			link.click();
			URL.revokeObjectURL(url);		})
	}
	
	const success = () => {
		ElMessage({message: '导入成功！', type: 'success',})
	}
</script>

<template>
	<div class="back">
		<el-card class="">
			<template #header>
				<div class="header">
					<el-button type="success" :icon="Plus" @click="showAddDialog">添加</el-button>
					<el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
					<el-button type="primary" :icon="Download" @click="exportExcel">导出Excel</el-button>
					<el-upload
						class="upload-demo"
						multiple=""
						method="post"
						action="/api/blog/importExcel"
						name="file"
						style="margin-left: 10px"
						accept=".xlsx,.xls"
						:show-file-list="false"
						:on-success="success"
						:headers="headers">
						<el-button type="primary" :icon="Upload">导入Excel</el-button>
					</el-upload>
				</div>
			</template>
			<!--		搜索框-->
			<el-form :inline="true" :model="formInline" class="demo-form-inline">
				<el-form-item label="博客标题">
					<el-input v-model="blogQuery.name" placeholder="请输入标题" clearable/>
				</el-form-item>
				<el-form-item label="博客类型">
					<el-select v-model="blogQuery.typeId" class="m-2"
							   clearable
							   placeholder="请选择博客类型"
							   @change='selectAllType'
							   ar='clearSelect' style='width:200px'>
						<el-option
							v-for="item in options"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="更新时间">
					<el-date-picker
						v-model="blogQuery.beginUpdateTime"
						type="datetime"
						value-format="YYYY-MM-DD HH:mm:ss"
						placeholder="开始时间"
					/>
					-
					<el-date-picker
						v-model="blogQuery.endUpdateTime"
						type="datetime"
						value-format="YYYY-MM-DD HH:mm:ss"
						placeholder="结束时间"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
					<el-button @click="resetForm" round>重置</el-button>
				</el-form-item>
			</el-form>
			
			<!--		信息表格-->
			<el-table ref="multipleTableRef" :data="blogList" border stripe style="width: 100%"
					  @selection-change="handleSelectionChange" height="450px">
				<el-table-column type="selection" :selectable="selectable" width="40"/>
				<el-table-column fixed prop="id" label="ID" sortable width="70" align="center"/>
				<el-table-column prop="name" label="博客标题" align="center" width="120" show-overflow-tooltip/>
				<el-table-column prop="typeName" label="博客类型" align="center" width="120"/>
<!--				<el-table-column prop="typeId" label="博客类型" align="center" width="120"/>-->
				<el-table-column prop="image" label="博客封面" align="center" width="180" show-overflow-tooltip>
					<template #default="scope">
						<img :src="scope.row.image" style="max-height: 40px;max-width: 120px"/>
					</template>
				</el-table-column>
				<el-table-column prop="clickCount" label="点击阅读量" align="center" width="100"/>
				<el-table-column prop="content" label="博客内容" align="center" width="90" show-overflow-tooltip/>
				<el-table-column prop="status" label="博客状态" align="center" width="130">
					<template #default="scope">
						<el-switch
							v-model="scope.row.status"
							class="ml-2"
							inline-prompt
							size="large"
							active-text="上架"
							:active-value="1"
							inactive-text="下架"
							:inactive-value="0"
							@change="handleSwitchChange(scope.row)"
						/>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" align="center" width="200"/>
				<el-table-column prop="updateTime" label="更新时间" align="center" width="200"/>
				<el-table-column fixed="right" label="操作" min-width="150" align="center">
					<template #default="{row}">
						<el-button type="info" :icon="Message" circle @click="handleClick(row.id)"/>
						<el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
						<el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)"/>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:current-page="blogQuery.page"
				v-model:page-size="blogQuery.limit"
				:page-sizes="[5, 10, 15, 20]"
				:size="size"
				:disabled="disabled"
				:background="background"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@change="loadData"
				style="margin-top: 20px; justify-content: flex-end"
			/>
		</el-card>
		
		<!--		添加编辑弹出框-->
		<el-dialog v-model="dialogVisible" title="添加、编辑" width="1000" :lock-scroll="false">
			<el-form :model="blog">
				<el-form-item label="博客标题：" :label-width="100">
					<el-input v-model="blog.name" autocomplete="off"/>
				</el-form-item>
				<el-form-item label="博客类型" :label-width="100">
					<el-select v-model="blog.typeId" class="m-2"
							   clearable
							   placeholder="请选择博客类型"
							   @change='selectAllType'
							   ar='clearSelect' style='width:200px'>
						<el-option
							v-for="item in options"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="博客封面：" :label-width="100">
					<el-upload
						class="avatar-uploader"
						action="/api/upload"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:headers="headers"
					>
						<img v-if="blog.image" :src="blog.image" class="avatar"/>
						<el-icon v-else class="avatar-uploader-icon">
							<Plus/>
						</el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="博客内容：" :label-width="100">
					<WangEditor :initValue="blog.content" @getEditorContent="onEditorChange"
								v-if="dialogVisible" @close="dialogVisible = false">
					</WangEditor>
				
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="addOrUpdate">
						确认
					</el-button>
				</div>
			</template>
		</el-dialog>
	</div>

</template>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	
	.upload-demo {
		display: inline;
		vertical-align: top;
	}
</style>
<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}
	
	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
	
</style>